﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using WPF.Core;
using WPF.Core.Dtos;
using WPF.Core.Services;

namespace WPF.NoteBook.ViewModels
{
    public partial class NoteBookViewModel : NavigateViewModel
    {
        private readonly INoteBookService appService;
        private readonly IHostDialogService dialog;

        [ObservableProperty]
        private NoteBookPagingInfo paging;

        [ObservableProperty]
        private ObservableCollection<NoteBookModel> gridModelList;

        public NoteBookViewModel(INoteBookService appService, IHostDialogService dialog)
        {
            Title = "记事本";
            this.appService = appService;
            this.dialog = dialog;
            Paging = new NoteBookPagingInfo()
            {
                PageNumber = 1,
                PageSize = 1,
            };
            GridModelList = new ObservableCollection<NoteBookModel>();
        }

        [RelayCommand]
        private async Task Search()
        {
            await GetAllAsync();
        }

        [RelayCommand]
        private async Task Add()
        {
            var dialogResult = await dialog.ShowDialogAsync("CreateNoteBookView");
            if (dialogResult.Result == ButtonResult.OK)
                await GetAllAsync();
        }

        [RelayCommand]
        private async Task Edit(NoteBookModel model)
        {
            DialogParameters param = new DialogParameters();
            param.Add("Value", model);

            var dialogResult = await dialog.ShowDialogAsync("CreateNoteBookView", param);

            if (dialogResult.Result == ButtonResult.OK)
                await GetAllAsync();
        }

        [RelayCommand]
        private async Task Delete(NoteBookModel model)
        {
            await appService.Delete(model.Id);
            var todo = GridModelList.FirstOrDefault(t => t.Id == model.Id);
            if (todo != null)
                GridModelList.Remove(todo);
        }

        [RelayCommand]
        private async Task Pageing()
        {
            await GetAllAsync();
        }

        private async Task GetAllAsync()
        {
            var models = await appService.GetAll(Paging);

            GridModelList.Clear();

            if (models != null)
            {
                foreach (var model in models)
                {
                    GridModelList.Add(model);
                }
            }
        }
    }
}
